<template>
  <el-form ref="changeAccountForm" :inline="false" :model="formObj.user" :rules="formObj.rules" label-position="right">
    <el-form-item :label="getLang('userName')" prop="userName">
      <el-input
        v-model.trim="formObj.user.userName"
        autocomplete="new-password"
        size="small"
        :placeholder="getPlholderInput('userName')"
        clearable
      />
    </el-form-item>
    <el-form-item :label="getLang('telNo')" prop="telNo">
      <el-input
        v-model.trim="formObj.user.telNo"
        autocomplete="new-password"
        size="small"
        :placeholder="getPlholderInput('telNo')"
        clearable
      />
    </el-form-item>
    <el-form-item :label="getLang('email')" prop="email">
      <el-input
        v-model.trim="formObj.user.email"
        autocomplete="new-password"
        size="small"
        :placeholder="getPlholderInput('email')"
        clearable
      />
    </el-form-item>
    <el-form-item>
      <el-button size="small" type="primary" @click="handleSaveProfile">
        {{ getLang('actions.updProfile') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import * as coreFnc from '../../common/utils/CoreFunction'
import * as app from '../../common/utils/BaseApp'
import * as ck from '../../common/utils/validater'
import { throttle } from '../../common/utils/throttle'

import store from '@/store'
import { updateUserProfile } from '@/api/system/user'
import langFile from '../profile.lang'
const base = app.install({ langObj: langFile })
export default {
  name: 'Account',
  mixins: [base],
  props: {
    user: {
      type: Object,
      default: () => { return { } }
    }
  },
  data() {
    return {
      formObj: {
        user: { ...this.user },
        rules: {
          userName: [ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 20)],
          telNo: [ck.createRequiredValidater(this), ck.createTelphoneOrMobileValidater(this)],
          email: [ck.createRequiredValidater(this), ck.createEMailValidater(this)]
        }
      }
    }
  },
  mounted() {
    coreFnc.createOnceWatch(this, 'user.userName', (newVal, oldVal) => {
      this.formObj.user = { ...this.user }
    })
  },
  methods: {
    handleSaveProfile: throttle.bind(this)(function() {
      coreFnc.createValidatePromise(this, 'changeAccountForm', async() => {
        await updateUserProfile({
          loginName: store.getters.loginName,
          userName: this.formObj.user.userName,
          telNo: this.formObj.user.telNo,
          email: this.formObj.user.email })

        setTimeout(() => {
          this.user.userName = this.formObj.user.userName
          this.user.telNo = this.formObj.user.telNo
          this.user.email = this.formObj.user.email
        }, 0)
      }, true)
    })
  }
}
</script>
<style lang="scss" scoped>
</style>

